//
//  pictureSelectController.swift
//  照片选择器
//
//  Created by 陈贵 on 15/9/25.
//  Copyright © 2015年 陈贵. All rights reserved.
//

private let HZJPICTURESELECTID = "HZJPICTURESELECTID"
/// 允许上传的最大图片数
private let HZJPICTURMAXCOUNT = 2

import UIKit


class pictureSelectController: UICollectionViewController,pictureSelectCellDelegate {
    
    
    //图片数组
    private lazy var pictures = [UIImage]()
    //记录当前所选图片的cell
    private var currentIndex = 0
    
    init(){
        let layout = UICollectionViewFlowLayout()
        layout.itemSize = CGSizeMake(80, 80)
        layout.sectionInset = UIEdgeInsetsMake(10, 10, 10, 10)
        super.init(collectionViewLayout: layout)
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override func viewDidLoad() {
        collectionView!.backgroundColor = UIColor(white: 0.9, alpha: 1)
       collectionView?.registerClass(pictureSelectCell.self, forCellWithReuseIdentifier: HZJPICTURESELECTID)
    }
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        
        return pictures.count + (pictures.count >= HZJPICTURMAXCOUNT ? 0 : 1)
    }
    
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(HZJPICTURESELECTID, forIndexPath: indexPath) as! pictureSelectCell
        //最后一个cell不加图片
        cell.cellImage = indexPath.item < pictures.count ? pictures[indexPath.item] : nil
        cell.CellDelegate = self
        return cell
    }
    
    //点击
    override func collectionView(collectionView: UICollectionView, didSelectItemAtIndexPath indexPath: NSIndexPath) {
        print(indexPath)
        if !UIImagePickerController.isSourceTypeAvailable(.SavedPhotosAlbum) {
            print("无法访问")
            return
        }
        
        currentIndex = indexPath.item
        
        //调用相册
        let iv = UIImagePickerController()
        iv.delegate = self
        
        //允许编辑
//        iv.allowsEditing = true
        
        //跳转至相册
        presentViewController(iv, animated: true, completion: nil)
        
    }

    //实现删除的代理方法
    private func pictureSelectCellRemoveCell(cell: pictureSelectCell) {
        let indexpath = collectionView?.indexPathForCell(cell)
        print(indexpath)
        //删除相应图片
        pictures.removeAtIndex((indexpath?.item)!)
        //刷新视图
        collectionView?.reloadData()
    }
}


extension pictureSelectController: UIImagePickerControllerDelegate, UINavigationControllerDelegate{
    
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        
        //压缩图片
        let getImage = image.getTheImage(image, toWidth: 150)
        
        //将图片添加到数组
        if currentIndex < pictures.count {
            pictures[currentIndex] = getImage
        }else{
            pictures.append(getImage)
        }
        
        //刷新视图
        collectionView?.reloadData()
        dismissViewControllerAnimated(true, completion: nil)
        
    }
    
}

/// MARK:-pictureSelectCellDelegate代理
private protocol pictureSelectCellDelegate: NSObjectProtocol{
     func pictureSelectCellRemoveCell(cell:pictureSelectCell)
}

/// MARK:-自定义cell
private class pictureSelectCell:UICollectionViewCell {
    
    
    //图片属性
    private var cellImage:UIImage?{
        didSet{
            
            print(cellImage)
            if ((cellImage) != nil) {
                pictureBth.setImage(cellImage, forState: .Normal)
            }else{
                pictureBth.setImage(UIImage(named: "compose_pic_add"), forState: .Normal)
            }
            //当无图片时隐藏关闭图标
            closeBth.hidden = cellImage == nil
        }
    }

    //代理
    var CellDelegate:pictureSelectCellDelegate?
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        
        setUI()
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    func setUI(){
        backgroundColor = UIColor.orangeColor()
        contentView.addSubview(pictureBth)
        contentView.addSubview(closeBth)
        //不可交互
        pictureBth.userInteractionEnabled = false
        //约束
        pictureBth.frame = bounds
        closeBth.translatesAutoresizingMaskIntoConstraints = false
        contentView.addConstraint(NSLayoutConstraint(item: closeBth, attribute: NSLayoutAttribute.Top, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Top, multiplier: 1, constant: 0))
        contentView.addConstraint(NSLayoutConstraint(item: closeBth, attribute: NSLayoutAttribute.Right, relatedBy: NSLayoutRelation.Equal, toItem: contentView, attribute: NSLayoutAttribute.Right, multiplier: 1, constant: 0))
        
        closeBth.addTarget(self, action: "clickTheCloseBth", forControlEvents: .TouchUpInside)
        
        pictureBth.imageView?.contentMode = .ScaleAspectFill
    }
    
    @objc func clickTheCloseBth(){
//        print("删除图片\(self)")
        
        CellDelegate?.pictureSelectCellRemoveCell(self)
    }
    
    ///MARK : - 懒加载
    //图片按钮
    private lazy var pictureBth:UIButton = UIButton(imageName: "compose_pic_add")
    //关闭按钮
    private lazy var closeBth:UIButton = UIButton(imageName: "compose_photo_close")

    
}





